package org.ligson.fwc.api.vo;


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ligson.fwc.api.util.JsonUtil;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ligson on 2016/3/17.
 * json返回对象
 */
@Data
@Slf4j
public class WebResult implements Serializable {
    private boolean success;
    private String errorCode;
    private String errorMsg;
    private Map<String, Object> data = new HashMap<>();


    public void clear() {
        data.clear();
        setSuccess(false);
        setErrorCode(null);
        setErrorMsg(null);
    }

    public <E> E getData(String key, Class<E> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        Object data = get(key);
        try {
            String json = JsonUtil.toJson(data);
            if (StringUtils.isNotBlank(json)) {
                return JsonUtil.readObject(json, clazz);
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public void put(String key, Object object) {
        data.put(key, object);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        if (data.containsKey(key)) {
            return (T) data.get(key);
        } else {
            return null;
        }

    }

    public static WebResult getSuccessInstance() {
        WebResult webResult = new WebResult();
        webResult.setSuccess(true);
        return webResult;
    }

    public static WebResult getFailInstance(String errorMsg) {
        WebResult webResult = new WebResult();
        webResult.setSuccess(false);
        webResult.setErrorMsg(errorMsg);
        return webResult;
    }

}
